package models

import (
	"gorm.io/gorm"
	"interview/pkg/utils"
	"time"
)

type BanRecord struct {
	Model
	UserOpenID string    `gorm:"comment:'用户openid,加密存储';column:'user_open_id';" json:"userOpenID"`
	BanTime    LocalTime `gorm:"comment:'封禁时间'" json:"banTime"`
	Reason     string    `gorm:"type:varchar(255);comment:'封禁理由'" json:"reason"`
	Executor   string    `gorm:"type:varchar(30);default '管理员'" json:"executor"`
}

func (m BanRecord) AfterFind(db *gorm.DB) (err error) {
	if m.UserOpenID != "" {
		m.UserOpenID = utils.AesDecrypt(m.UserOpenID)
	}
	return
}

func (m BanRecord) BeforeSave(db *gorm.DB) (err error) {
	if m.UserOpenID != "" {
		m.UserOpenID = utils.AesEncrypt(m.UserOpenID)
	}
	return
}

// TableName 修改默认表名
func (BanRecord) TableName() string {
	return TableName("ban_record")
}

// CreateBanRecord 创建封禁记录
func CreateBanRecord(data map[string]interface{}) (uint, error) {
	tx := db.Begin()
	defer func() {
		if e := recover(); e != nil {
			tx.Rollback()
		} else {
			tx.Commit()
		}
	}()

	r := BanRecord{
		UserOpenID: data["openID"].(string),
		BanTime:    LocalTime{time.Now()},
		Reason:     data["reason"].(string),
		Executor:   "管理员",
	}

	tx.Create(&r)

	user, _ := FindUserByOpenID(r.UserOpenID)
	b := false

	err := tx.Model(&User{}).Where("id", user.ID).Updates(&User{Status: &b}).Error
	if err != nil {
		return 0, err
	}

	return r.ID, nil
}

func FindBanRecordList(pageNum, pageSize int, filters map[string]interface{}) ([]*BanRecord, int64, error) {
	var (
		records []*BanRecord
		total   int64
	)
	err := db.Model(&BanRecord{}).Where(filters).Scopes(Paginate(pageNum, pageSize)).Count(&total).Find(&records).Error
	if err != nil {
		return nil, 0, err
	}
	return records, total, nil
}
